package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.Movies;
import com.itheima.domain.MoviesExample;
import com.itheima.mapper.MoviesMapper;
import com.itheima.service.MovieService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class MoviesServiceImp implements MovieService {
    @Autowired
    private MoviesMapper moviesMapper;


    @Override
    public PageInfo<Movies> findByPage(Integer pageNum, Integer pageSize) {
        /*开启分页拦截*/
        PageHelper.startPage(pageNum, pageSize);
        MoviesExample moviesExample = new MoviesExample();
        //根据上映时间降序
        moviesExample.setOrderByClause("show_time desc");
        //查询所有
        List<Movies> movies = moviesMapper.selectByExample(null);
        PageInfo<Movies> pageInfo = new PageInfo<>(movies);
        return pageInfo;

    }
    /*根据cid查询或者关键字查询*/
    @Override
    public PageInfo<Movies> findByPage(Integer pageNum, Integer pageSize, Integer cid, String keyword) {
        //开启分页拦截
        PageHelper.startPage(pageNum, pageSize);
        //根据条件查询：根据cid查询或者关键字查询
        MoviesExample moviesExample = new MoviesExample();
        //根据上映时间降序
        moviesExample.setOrderByClause("show_time desc");
        //获取条件对象
        MoviesExample.Criteria criteria = moviesExample.createCriteria();
        if (cid != null) {
            criteria.andCidEqualTo(cid);
        }
        //根据关键字模糊查询
        if (keyword != null && !keyword.equals("")) {
            criteria.andKeywordLike("%" + keyword + "%");
        }
        List<Movies> movies = moviesMapper.selectByExample(moviesExample);
        return new PageInfo<>(movies);

    }

    /*//添加或修改电影的方法*/

    @Override
    public void save(Movies movies) {
        /*判断是否有id，从而判断是添加还是修改*/
        if (movies.getId() != null) {
            //说明是修改
            moviesMapper.updateByPrimaryKeySelective(movies);
        } else {
            //添加的方法
            moviesMapper.insert(movies);
        }
    }
    /*根据id查询*/

    @Override
    public Movies findById(Integer id) {
        Movies movies = moviesMapper.selectByPrimaryKey(id);
        return movies;
    }

    //    //根据id删除

    @Override
    public void deleteById(Integer id) {
        moviesMapper.deleteByPrimaryKey(id);
    }
    /*批量删除*/
    @Override
    public void deleteBatch(Integer[] ids) {
        for (Integer id : ids) {
            moviesMapper.deleteByPrimaryKey(id);
        }


    }
}
